package com.zjdiepu.www.biz.yw;

import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.AddedStatus1;
import com.zjdiepu.www.base.enums.status.AuditListStatus;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.InterviewConfigStatus;
import com.zjdiepu.www.base.enums.status.InterviewStatus;
import com.zjdiepu.www.base.enums.status.LessInformationStatus;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.SysParamsType;
import com.zjdiepu.www.base.enums.type.TypeData;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.dao.cw.CwRemitCarMapper;
import com.zjdiepu.www.dao.fk.FkAuditListMapper;
import com.zjdiepu.www.dao.other.OtherAuditInfoMapper;
import com.zjdiepu.www.dao.other.OtherWantWarningMapper;
import com.zjdiepu.www.dao.yw.YwBusinessLoanMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.dao.yw.YwFeesMapper;
import com.zjdiepu.www.dao.yw.YwFundApplyMapper;
import com.zjdiepu.www.ibiz.file.IQiniuFileService;
import com.zjdiepu.www.ibiz.fk.IFkAuditListService;
import com.zjdiepu.www.ibiz.other.IOtherInterviewConfigService;
import com.zjdiepu.www.ibiz.system.IBaseBusiUnitService;
import com.zjdiepu.www.ibiz.system.IBaseSalersmanService;
import com.zjdiepu.www.ibiz.system.IBaseSysParamsService;
import com.zjdiepu.www.ibiz.yw.IYwFundApplyService;
import com.zjdiepu.www.ibiz.zpp.FengKongShenHeService;
import com.zjdiepu.www.ibiz.zx.IZxQueryCreditApplyService;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.cw.dto.CwRemitCar;
import com.zjdiepu.www.model.cw.ext.CwRemitCarExt;
import com.zjdiepu.www.model.fk.dto.FkAuditList;
import com.zjdiepu.www.model.other.dto.OtherAuditInfo;
import com.zjdiepu.www.model.other.dto.OtherInterviewConfig;
import com.zjdiepu.www.model.other.dto.OtherWantWarning;
import com.zjdiepu.www.model.system.dto.BaseBusiUnit;
import com.zjdiepu.www.model.system.dto.BaseSalersman;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwFees;
import com.zjdiepu.www.model.yw.dto.YwFundApply;
import com.zjdiepu.www.model.yw.ext.YwFundApplyExt;
import com.zjdiepu.www.model.yw.response.YwBusinessDetail;
import com.zjdiepu.www.model.zx.dto.ZxQueryCreditApply;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * 申请垫资Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月09日 09时29分<br/>
 * @since 1.0<br/>
 */
@Service
public class YwFundApplyServiceImpl extends BaseService implements IYwFundApplyService {
	public static final Logger logger = LoggerFactory.getLogger(YwFundApplyServiceImpl.class);

	@Autowired
	private IFkAuditListService fkAuditListService;
	@Autowired
	private YwFeesMapper ywFeesMapper;
	@Autowired
	private YwFundApplyMapper ywFundApplyMapper;
	@Autowired
	private CwRemitCarMapper cwRemitCarMapper;
	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private YwBusinessLoanMapper ywBusinessLoanMapper;
	@Autowired
	private OtherWantWarningMapper otherWantWarningMapper;
	@Autowired
	private OtherAuditInfoMapper otherAuditInfoMapper;
	@Autowired
	private FkAuditListMapper fkAuditListMapper;
	@Autowired
	private IBaseSysParamsService baseSysParamsService;
	@Autowired
	private IQiniuFileService qiniuFileService;
	@Resource
    private IOtherInterviewConfigService otherInterviewConfigService;
	@Resource
	private IZxQueryCreditApplyService zxQueryCreditApplyService;
	@Resource
	private IBaseBusiUnitService baseBusiUnitService;
	@Resource
	private IBaseSalersmanService baseSalersmanService;
	@Autowired
	private FengKongShenHeService fengKongShenHeService;
	
	@Override
	public YwFundApply getApplyNotRemit(String busiId) {
		if(StringUtils.isBlank(busiId)) {
			return null;
		}
		YwFundApplyExt ywFundApplyExt = new YwFundApplyExt();
		ywFundApplyExt.setBaseWhere();
		ywFundApplyExt.withOutPage();
		ywFundApplyExt.setBusiId(busiId);
		List<YwFundApply> ywFundApplys = ywFundApplyMapper.selectByExt(ywFundApplyExt);
		if(CollectionUtils.isEmpty(ywFundApplys)) {
			return null;
		}
		outter:for(YwFundApply ywFundApply : ywFundApplys) {
			CwRemitCarExt cwRemitCarExt = new CwRemitCarExt();
			cwRemitCarExt.setBaseWhere();
			cwRemitCarExt.withOutPage();
			cwRemitCarExt.setBusiId(busiId);
			List<CwRemitCar> cwRemitCars = cwRemitCarMapper.selectByExt(cwRemitCarExt);
			for(CwRemitCar cwRemitCar : cwRemitCars) {
				if(ywFundApply.getId().equals(cwRemitCar.getFundApplyId())) { //已经垫资
					continue outter;
				}
			}
			return ywFundApply;
		}
		return null;
	}
	
	@Override
	public ApiResponse saveApplyFund(YwFundApply ywFundApply,
			SysUser sysUser,String serverRealPath) {
		String userId = sysUser.getId();
		String userName = sysUser.getName();
		
		String busiId = ywFundApply.getBusiId();
		YwBusinessDetail ywBusinessDetail = ywBusinessMapper.selectMultiByPrimaryKey(busiId);
		if(null == ywBusinessDetail) {
			ExceptionHelper.thow(ResultFlagType.MISSING.getCode().toString(), "业务记录不存在或已被删除");
		}
		String salesmanId = ywBusinessDetail.getSalesmanId();
		BaseSalersman baseSalersman = baseSalersmanService.selectById(salesmanId);
		if(null == baseSalersman) {
			ExceptionHelper.thow(ResultFlagType.MISSING.getCode().toString(), "业务员记录不存在或已被删除");
		}
		String unitId = baseSalersman.getUnitId();
		BaseBusiUnit baseBusiUnit = baseBusiUnitService.selectById(unitId);
		if(null == baseBusiUnit) {
			ExceptionHelper.thow(ResultFlagType.MISSING.getCode().toString(), "业务单位不存在或已被删除");
		}
		
		// 手工模式不需要限定面签 2018-04-01
		String queryCreditApplyId = ywBusinessDetail.getQueryCreditApplyId();
		boolean auto = false;
		if(StringUtils.isNotBlank(queryCreditApplyId)) {
			ZxQueryCreditApply zxQueryCreditApply = zxQueryCreditApplyService.selectById(queryCreditApplyId);
			if(null == zxQueryCreditApply) {
				ExceptionHelper.thow(ResultFlagType.MISSING.getCode().toString(), "征信申请记录不存在或已被删除");
			}
			if(TypeData.HZICBC.getCode().equals(zxQueryCreditApply.getTypeData())) {
				auto = true;
			}
		}
		
		if(auto) {
			OtherInterviewConfig otherInterviewConfig = otherInterviewConfigService.getOtherInterviewConfigBySalesmanId(ywBusinessDetail.getLoanBank(), ywBusinessDetail.getSalesmanId());
			if(null != otherInterviewConfig) {
				String interviewConfigStatus = otherInterviewConfig.getInterviewConfigStatus();
				if(InterviewConfigStatus.XU_YAO_MIAN_QIAN.getCode().equals(interviewConfigStatus)) {
					Integer interviewStatus = ywBusinessDetail.getInterviewStatus();
					if(!InterviewStatus.MIAN_QIAN_CHENG_GONG.getCode().equals(interviewStatus) && !InterviewStatus.XU_YAO_ER_CI_MIAN_QIAN.getCode().equals(interviewStatus)) {
						ExceptionHelper.thow(ResultFlagType.APPLY_FUND_NOLY_INTERVIEW_SUCCESS.getCode().toString(), 
								String.format(ResultFlagType.APPLY_FUND_NOLY_INTERVIEW_SUCCESS.getValue(), baseBusiUnit.getOrgName()+"(" +  baseBusiUnit.getOrgCode() + ")")); //面签成功才能申请垫资
					}
				}
			}
		}
		
		Integer lessInformationStatus = ywBusinessDetail.getLessInformationStatus();
		if(LessInformationStatus.QIAN_ZI_LIAO.getCode().equals(lessInformationStatus)) {
			ExceptionHelper.thow("999", "欠资料状态不能申请垫资");
		}
		
		Date timeAuditFinish = ywBusinessDetail.getTimeAuditFinish();
		
		//zhangpp  207-06-10
		int countDiffDateDays = 0;
		if(null != timeAuditFinish){
			countDiffDateDays = DateUtil.countDiffDateDays(timeAuditFinish, new Date());
		}
		
		//垫款申请距审核完成的时间
		Integer overdueFundRetrial = (Integer)SysParamsType.DIAN_ZI_CHAO_QI_CHONG_SHEN.getDefaultValue();;
		String overdueFundRetrialValue = baseSysParamsService.getValueByCode(SysParamsType.DIAN_ZI_CHAO_QI_CHONG_SHEN.getCode());
		if(StringUtils.isNotBlank(overdueFundRetrialValue)) {
			overdueFundRetrial = Integer.parseInt(overdueFundRetrialValue);
		}
		
		if(countDiffDateDays > overdueFundRetrial) { //垫资超期，申请不保存
//			2018-01-29如果判断为超期，需要 先将原先未审核的待列表（fk_audit_list）的dp_status设置为3（本次新增）
			FkAuditList fkAuditListDelete = new FkAuditList();
			fkAuditListDelete.setDpStatus(DpStatus.NORMAL.getCode());
			fkAuditListDelete.setStatusList(AuditListStatus.WEI_SHEN_PI.getCode());
			fkAuditListDelete.setBusiId(busiId);
			fkAuditListService.deletedRefined(fkAuditListDelete);
			
//			FkAuditList fkAuditList = new FkAuditList();
//			fkAuditList.setDpStatus(DpStatus.NORMAL.getCode());
//			fkAuditList.setModeId(ModeIDType.ZSYS.getCode());
//			fkAuditList.setBusiId(busiId);
//			fkAuditList.setStatusList(AuditListStatus.WEI_SHEN_PI.getCode()); //未审批
//			int countRefined = fkAuditListMapper.countRefined(fkAuditList); //资审一审未审批记录数目
			
//			@update 又多次申请超期的 2017-11-10
//			OtherAuditInfo otherAuditInfo = new OtherAuditInfo();
//			otherAuditInfo.setDpStatus(DpStatus.NORMAL.getCode());
//			otherAuditInfo.setModeId(ModeIDType.DZSH.getCode());
//			otherAuditInfo.setDataId(busiId);
//			int countRefined = otherAuditInfoMapper.countRefined(otherAuditInfo);
//			if(countRefined == 0) { //还没有生成超期重审 自动审核记录
				
				OtherAuditInfo otherAudit = new OtherAuditInfo();
				otherAudit.initInsertData(userId, userName);
				otherAudit.setModeId(ModeIDType.DZSH.getCode());
				otherAudit.setBusiId(busiId);
				otherAudit.setDataId(busiId);
				otherAudit.setAuditName("垫资超期重审");
				otherAudit.setOrgCode(sysUser.getOrgId());
				otherAudit.setOrgName(sysUser.getOrgName());
				otherAudit.setAuditStatus(AuditListStatus.SHEN_PI_BU_TONG_GUO.getCode().toString()); //重审，等效为不通过
				otherAuditInfoMapper.insert(otherAudit);
				
				fkAuditListService.insertFkAuditList(ywBusinessDetail, ModeIDType.ZSYS, "垫资超期重审", sysUser);
				
				YwBusiness ywBusiness = new YwBusiness();
				ywBusiness.setId(busiId);
//				ywBusiness.setSubmitTime(new Date());
				ywBusiness.setBusiStatus(BusiStatus.ZI_SHEN_YI_SHEN_ZHONG.getCode());
//				并且如果欠资料状态为“欠资料”，将“欠资料状态更改为“资料齐全”（5.23修改）
				ywBusiness.setLessInformationStatus(LessInformationStatus.ZI_LIAO_QI_QUAN.getCode());
				ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
				try  {
					//自动审核  资审一审
					String[] modeId = {ModeIDType.ZSYS.getCode()};
					fengKongShenHeService.diepuZiDongShenWaiBu(sysUser,modeId,ywBusinessDetail.getId(),serverRealPath);
				} catch (Exception e) {
					logger.error(e.getMessage());
				} finally {
					logger.debug("自动审核执行完毕");
				}
//			}
			return ApiResponse.fail(999, "申请垫资超期，需要重新审核");
		}
		
		//字段填充feesId
		String id = ywFundApply.getId();
		if(StringUtils.isBlank(ywFundApply.getFeesId())) {
			YwFees ywFees = new YwFees();
			ywFees.setDpStatus(DpStatus.NORMAL.getCode());
			ywFees.setBusiId(busiId);
			ywFees = ywFeesMapper.selectRefined(ywFees);
			if(null != ywFees) {
				ywFundApply.setFeesId(ywFees.getId());
			} else {
				ExceptionHelper.thow("999","按揭日报表缺失");
			}
		}
		
		if(StringUtils.isNotBlank(id)) {
			ywFundApply.initUpdateData(userId, userName);
			ywFundApplyMapper.updateByPrimaryKeySelective(ywFundApply);
		} else {
			ywFundApply.initInsertData(userId, userName);
			ywFundApplyMapper.insert(ywFundApply);
		}
		//如果资金流程状态为‘按揭日报表已登记’，‘已退款’，将资金流程状态（added_status1）改为“财务一审核中”，去掉 【将业务数据状态改为“财务一审核中”】
		YwBusiness ywBusiness = ywBusinessMapper.selectByPrimaryKey(busiId);
		if(AddedStatus1.AN_JIE_RI_BAO_BIAO_YI_DENG_JI.getCode().equals(ywBusiness.getAddedStatus1()) 
				|| AddedStatus1.YI_TUI_KUAN.getCode().equals(ywBusiness.getAddedStatus1())) { //按揭日表表或已退款再申请
			YwFundApply ywFundApply_ = new YwFundApply();
			ywFundApply_.setBusiId(busiId);
			ywFundApply_.setDpStatus(DpStatus.NORMAL.getCode());
			int countYwFundApply_= ywFundApplyMapper.countRefined(ywFundApply_);
			
			FkAuditList fkAuditList = new FkAuditList();
			fkAuditList.setBusiId(busiId);
			fkAuditList.setDpStatus(DpStatus.NORMAL.getCode());
			fkAuditList.setModeId(ModeIDType.CWSHHY.getCode());
			int countRefined = fkAuditListMapper.countRefined(fkAuditList);
			if(countRefined < countYwFundApply_) { //还没有生成
				fkAuditListService.insertFkAuditList(ywBusinessDetail, ModeIDType.CWSHHY, "申请垫资", sysUser);
			}
			
			ywBusiness.setAddedStatus1(AddedStatus1.CAI_WU_YI_SHEN_HE_ZHONG.getCode());
			ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
		}
		
		//触发附件打包功能(并不是已经生成，需要等待任务查询状态确认)
		qiniuFileService.saveRar(busiId, ywBusiness.getQueryCreditApplyId());
		
		//删除申请垫资预警信息
		OtherWantWarning dzOtherWantWarning = new OtherWantWarning();
		dzOtherWantWarning.setBusiId(busiId);
		dzOtherWantWarning.setModeId(ModeIDType.SQDDZ.getCode());
		otherWantWarningMapper.deletedReal(dzOtherWantWarning);
				
		return ApiResponse.success(true);
	}
	
	@Override
	public void saveUpdateAndDelete(YwFundApply ywFundApply, OperateType operType) {
		switch (operType) {
		case add:
			ywFundApply.initInsertData(ywFundApply.getModifier(), ywFundApply.getModifierName());
			ywFundApplyMapper.insert(ywFundApply);
			break;
		case edit:
			ywFundApply.initUpdateData(ywFundApply.getModifier(), ywFundApply.getModifierName());
			// 影响的记录数
			int updateCount = ywFundApplyMapper.updateByPrimaryKeySelective(ywFundApply);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			ywFundApply.initDeleteData(ywFundApply.getModifier(), ywFundApply.getModifierName());
			// 影响的记录数
			int deleteCount = ywFundApplyMapper.updateByPrimaryKeySelective(ywFundApply);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<YwFundApply> selectByExt(YwFundApplyExt ywFundApplyExt) {
		return ywFundApplyMapper.selectByExt(ywFundApplyExt);
	}
	
	@Override
	public int countByExt(YwFundApplyExt ywFundApplyExt){
		return ywFundApplyMapper.countByExt(ywFundApplyExt);
	}
	
	@Override
	public YwFundApply selectById(String id) {
		return ywFundApplyMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			ywFundApplyMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(YwFundApply ywFundApply) {
		return ywFundApplyMapper.countRefined(ywFundApply);
	}

	@Override
	public YwFundApply selectRefined(YwFundApply ywFundApply) {
		return ywFundApplyMapper.selectRefined(ywFundApply);
	}
	
	@Override
	public int deletedRefined(YwFundApply ywFundApply) {
		return ywFundApplyMapper.deletedRefined(ywFundApply);
	}

	@Override
	public boolean repeat(YwFundApply ywFundApply) {
		int count = countRefined(ywFundApply);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(ywFundApply.getId())) {
			return true;
		}
		YwFundApply dbItem = selectRefined(ywFundApply);
		if(null == dbItem) {
			return false;
		}
		return !ywFundApply.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return ywFundApplyMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<YwFundApply> ywFundApplys) {
		return ywFundApplyMapper.insertBatch(ywFundApplys);
	}
}
